<template>
  <div class="main">
    <div class="main_panle">
      <div class="login_form" style="['width': modelWidth]">
        <div class="login_form_title ">
          欢迎登录后台管理系统
        </div>
        <div class="login_form_panle">
          <a-form
            id="formLogin"
            class="user-layout-login_form"
            ref="formLogin"
            :form="form"
            @submit="handleSubmit"
          >
            <a-tabs
              :activeKey="customActiveKey"
              :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
              @change="handleTabClick"
            >
              <a-tab-pane key="tab1" tab="账号密码">
                <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px;" message="账号密码错误" />
                <a-form-item>
                  <a-input
                    size="large"
                    type="text"
                    class="form_item_input"
                    placeholder="请输入账号"
                    autocomplete
                    v-decorator="[
                      'username',
                      {rules: [{ required: true, message:'手机号码必须填写'}, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
                    ]"
                  >
                    <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                  </a-input>
                </a-form-item>

                <a-form-item>
                  <a-input-password
                    size="large"
                    placeholder="请输入密码"
                    autocomplete
                    class="form_item_input"
                    v-decorator="[
                      'password',
                      {rules: [{ required: true, message: '密码必须填写' }], validateTrigger: 'blur'}
                    ]"
                  >
                    <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                  </a-input-password>
                </a-form-item>
              </a-tab-pane>
              <a-tab-pane key="tab2" tab="验证码登陆">
                <a-form-item>
                  <a-input class="form_item_input" size="large" type="text" placeholder="请输入手机号码" v-decorator="['mobile', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message:'请输入手机号码' }], validateTrigger: 'change'}]">
                    <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                  </a-input>
                </a-form-item>

                <a-row :gutter="16">
                  <a-col class="gutter-row" :span="16">
                    <a-form-item>
                      <a-input class="form_item_input" size="large" type="text" placeholder="请输入验证码" v-decorator="['captcha', {rules: [{ required: true, message:'请输入验证码' }], validateTrigger: 'blur'}]">
                        <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                      </a-input>
                    </a-form-item>
                  </a-col>
                  <a-col class="gutter-row" :span="8">
                    <a-button
                      class="getCaptcha"
                      tabindex="-1"
                      :disabled="state.smsSendBtn"
                      @click.stop.prevent="getCaptcha"
                      v-text="!state.smsSendBtn && '获取验证码' || ('已发送'+state.time+' s')"
                    ></a-button>
                  </a-col>
                </a-row>
              </a-tab-pane>
            </a-tabs>

            <a-form-item style="margin-top:24px">
              <a-button
                size="large"
                type="primary"
                htmlType="submit"
                class="login-button"
                :loading="state.loginBtn"
                :disabled="state.loginBtn"
              >登录</a-button>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
export default {
  name: 'Login',
  data () {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      },
    modelWidth: this.$store.getters.modelWidth
    }
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick (key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this

      state.loginBtn = true
      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha']
      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values }
          delete loginParams.username
          loginParams[!state.loginType ? 'email' : 'phone'] = values.username
          loginParams.password = (values.password)
          loginParams.type = 'web'
          console.log('登陆', loginParams)
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)
          setTimeout(hide, 1000)
          // clearInterval(interval)
          // state.time = 60
          // state.smsSendBtn = false
          // getSmsCaptcha({ mobile: values.mobile }).then(res => {
          //   setTimeout(hide, 2500)
          //   this.$notification['success']({
          //     message: '提示',
          //     description: '验证码获取成功，您的验证码为：' + res.result.captcha,
          //     duration: 8
          //   })
          // }).catch(err => {
          //
          //   this.requestFailed(err)
          // })
        }
      })
    },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess (res) {
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
      this.$router.push({ name: 'analysis' }, () => {
        console.log('onComplete')
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      })
      */
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed (err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>

<style scoped lang='less'>
.main{
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-image: url('../../assets/image/login/login_background.png');
  background-size: cover;
  position: relative;
  .main_panle{
    position: absolute;
    top: 5%;
    left: 3%;
    width: 94%;
    height: 90%;
    overflow: hidden;
    background-image: url('../../assets/image/login/login_panle.png');
    background-size: cover;
    border-radius: 20px;
    padding: 10%;
    box-shadow: 0px 1px 20px 1px rgba(0,0,0,.1);
    .login_form{
      height: 90%;
      float: right;

      .login_form_title{
        font-size: 40px;
        font-weight: 500;
        color: #333333;
        line-height: 0px;
      }
      .form_item_input{
        height: 50px;
        line-height: 50px;
      }
      .login_form_panle{
        margin-top: 64px;
        width: 500px;
      }
      .login-button{
        width: 500px;
        height: 50px;

      }
    }
  }
}
.getCaptcha{
  margin-top: 5px;
  width: 100%;
  height: 40px;
}
/deep/.ant-btn span {
  font-weight: 500;
  font-size: 22px;
  line-height: 24px;
}
/deep/.ant-tabs-tab{
  font-size: 16px;
  width: 80%;
}
/deep/.ant-tabs-nav-scroll{
  margin-left: -40%;

}
</style>
